class RealtimeMonitoring {
    constructor() {
        this.charts = {};
        
        // 等待 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        this.initializeCharts();
        this.initializeEventListeners();
        this.updateData();
        this.startRealTimeUpdate();
    }

    initializeCharts() {
        // 初始化实时趋势图
        const trendCtx = document.getElementById('realtimeTrendChart');
        if (trendCtx) {
            this.charts.trendChart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: Array.from({length: 60}, (_, i) => i + 1),
                    datasets: [{
                        label: '实时数据',
                        data: this.generateMockData(60),
                        borderColor: '#1890ff',
                        tension: 0.4,
                        fill: false
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '数值'
                            }
                        }
                    }
                }
            });
        }

        // 初始化数据分布图
        const distributionCtx = document.getElementById('dataDistributionChart');
        if (distributionCtx) {
            this.charts.distributionChart = new Chart(distributionCtx, {
                type: 'bar',
                data: {
                    labels: ['0-20%', '20-40%', '40-60%', '60-80%', '80-100%'],
                    datasets: [{
                        label: '数据分布',
                        data: this.generateMockData(5),
                        backgroundColor: 'rgba(24, 144, 255, 0.6)',
                        borderColor: '#1890ff',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '数量'
                            }
                        }
                    }
                }
            });
        }

        // 初始化传感器状态图
        const statusCtx = document.getElementById('sensorStatusChart');
        if (statusCtx) {
            this.charts.statusChart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['正常', '异常', '离线', '低电量'],
                    datasets: [{
                        data: [24, 1, 0, 2],
                        backgroundColor: [
                            '#52c41a',
                            '#faad14',
                            '#ff4d4f',
                            '#faad14'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right'
                        }
                    }
                }
            });
        }
    }

    initializeEventListeners() {
        // 传感器类型选择事件
        document.getElementById('sensor-type-selector')?.addEventListener('change', () => {
            this.updateSensorData();
        });

        // 区域选择事件
        document.getElementById('sensor-area-selector')?.addEventListener('change', () => {
            this.updateSensorData();
        });

        // 刷新按钮点击事件
        const refreshBtn = document.querySelector('.realtime-monitoring-panel .refresh-btn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                refreshBtn.classList.add('refreshing');
                refreshBtn.querySelector('i').classList.add('fa-spin');
                
                this.updateData();
                
                setTimeout(() => {
                    refreshBtn.classList.remove('refreshing');
                    refreshBtn.querySelector('i').classList.remove('fa-spin');
                }, 1000);
            });
        }

        // 趋势图时间范围选择
        document.querySelectorAll('.time-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
                this.updateTrendChart(e.target.dataset.range);
            });
        });

        // 分析类型选择事件
        document.getElementById('analysis-type-selector')?.addEventListener('change', () => {
            this.updateAnalysisData();
        });
    }

    generateMockData(count, min = 0, max = 100) {
        return Array.from({length: count}, () => min + Math.random() * (max - min));
    }

    updateData() {
        this.updateSensorData();
        this.updateTrendChart();
        this.updateAnalysisData();
        this.updateStatusData();
    }

    updateSensorData() {
        const tbody = document.getElementById('sensor-data-body');
        if (!tbody) return;

        const typeFilter = document.getElementById('sensor-type-selector').value;
        const areaFilter = document.getElementById('sensor-area-selector').value;
        
        const mockData = this.generateMockSensorData(typeFilter, areaFilter);
        
        tbody.innerHTML = mockData.map(sensor => `
            <tr>
                <td>${sensor.id}</td>
                <td>${sensor.type}</td>
                <td>${sensor.area}</td>
                <td>
                    <span class="sensor-value ${sensor.valueStatus}">
                        ${sensor.value}${sensor.unit}
                    </span>
                </td>
                <td>
                    <span class="status-tag ${sensor.status.class}">
                        ${sensor.status.text}
                    </span>
                </td>
                <td>
                    <div class="signal-strength ${sensor.signal.class}">
                        <i class="fas fa-signal"></i>
                        <span>${sensor.signal.text}</span>
                    </div>
                </td>
                <td>
                    <div class="battery-level ${sensor.battery.class}">
                        <i class="fas ${sensor.battery.icon}"></i>
                        <span>${sensor.battery.value}%</span>
                    </div>
                </td>
                <td>${sensor.updateTime}</td>
                <td>
                    <button class="action-btn" onclick="alert('查看详情功能即将上线')">
                        <i class="fas fa-chart-line"></i>
                    </button>
                </td>
            </tr>
        `).join('');
    }

    generateMockSensorData(typeFilter, areaFilter) {
        const sensors = [];
        const types = {
            'moisture': { name: '土壤墒情', unit: '%', range: [0, 100] },
            'temperature': { name: '土壤温度', unit: '°C', range: [10, 40] },
            'ec': { name: '电导率', unit: 'ms/cm', range: [0, 5] },
            'ph': { name: 'pH值', unit: '', range: [0, 14] },
            'npk': { name: 'NPK含量', unit: 'mg/kg', range: [0, 1000] }
        };
        
        const count = 25;
        
        for (let i = 1; i <= count; i++) {
            const typeKey = Object.keys(types)[Math.floor(Math.random() * Object.keys(types).length)];
            const type = types[typeKey];
            const area = `区域${Math.ceil(i / 5)}`;
            
            if ((typeFilter === 'all' || typeFilter === typeKey) &&
                (areaFilter === 'all' || areaFilter === `area${Math.ceil(i / 5)}`)) {
                
                const value = (type.range[0] + Math.random() * (type.range[1] - type.range[0])).toFixed(1);
                const status = this.getSensorStatus();
                
                sensors.push({
                    id: `SEN${String(i).padStart(3, '0')}`,
                    type: type.name,
                    area: area,
                    value: value,
                    unit: type.unit,
                    valueStatus: this.getValueStatus(value, type.range),
                    status: status,
                    signal: this.getSignalStrength(),
                    battery: this.getBatteryStatus(),
                    updateTime: new Date(Date.now() - Math.random() * 3600000).toLocaleString()
                });
            }
        }
        
        return sensors;
    }

    getValueStatus(value, range) {
        const percent = (value - range[0]) / (range[1] - range[0]) * 100;
        if (percent < 20) return 'low';
        if (percent > 80) return 'high';
        return 'normal';
    }

    getSensorStatus() {
        const statuses = [
            { text: '正常', class: 'normal' },
            { text: '异常', class: 'warning' },
            { text: '离线', class: 'danger' }
        ];
        
        const weights = [0.8, 0.15, 0.05]; // 权重分布
        const random = Math.random();
        let sum = 0;
        
        for (let i = 0; i < weights.length; i++) {
            sum += weights[i];
            if (random <= sum) return statuses[i];
        }
        
        return statuses[0];
    }

    getSignalStrength() {
        const signals = [
            { text: '强', class: 'strong' },
            { text: '中', class: 'medium' },
            { text: '弱', class: 'weak' }
        ];
        
        return signals[Math.floor(Math.random() * signals.length)];
    }

    getBatteryStatus() {
        const battery = Math.floor(Math.random() * 100);
        let icon, className;
        
        if (battery > 75) {
            icon = 'fa-battery-full';
            className = 'high';
        } else if (battery > 50) {
            icon = 'fa-battery-three-quarters';
            className = 'medium';
        } else if (battery > 25) {
            icon = 'fa-battery-half';
            className = 'medium';
        } else if (battery > 10) {
            icon = 'fa-battery-quarter';
            className = 'low';
        } else {
            icon = 'fa-battery-empty';
            className = 'critical';
        }
        
        return {
            value: battery,
            icon: icon,
            class: className
        };
    }

    updateTrendChart(timeRange = '1h') {
        const points = timeRange === '1h' ? 60 : 
                      timeRange === '6h' ? 360 : 
                      1440; // 24h
        
        const data = this.generateMockData(points);
        this.charts.trendChart.data.labels = Array.from({length: points}, (_, i) => i + 1);
        this.charts.trendChart.data.datasets[0].data = data;
        this.charts.trendChart.update();
    }

    updateAnalysisData() {
        const type = document.getElementById('analysis-type-selector').value;
        const data = this.generateMockData(100);
        
        // 更新统计值并添加动画效果
        const updateStatValue = (id, value) => {
            const element = document.getElementById(id);
            if (element) {
                element.classList.add('updating');
                element.textContent = value;
                setTimeout(() => {
                    element.classList.remove('updating');
                }, 500);
            }
        };

        updateStatValue('stat-average', (data.reduce((a, b) => a + b, 0) / data.length).toFixed(1));
        updateStatValue('stat-max', Math.max(...data).toFixed(1));
        updateStatValue('stat-min', Math.min(...data).toFixed(1));
        updateStatValue('stat-std', this.calculateStandardDeviation(data).toFixed(1));

        // 更新分布图
        const distribution = this.calculateDistribution(data);
        this.charts.distributionChart.data.datasets[0].data = distribution;
        this.charts.distributionChart.update();
    }

    calculateStandardDeviation(data) {
        const mean = data.reduce((a, b) => a + b, 0) / data.length;
        const variance = data.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / data.length;
        return Math.sqrt(variance);
    }

    calculateDistribution(data) {
        const distribution = new Array(5).fill(0);
        data.forEach(value => {
            const index = Math.min(Math.floor(value / 20), 4);
            distribution[index]++;
        });
        return distribution;
    }

    updateStatusData() {
        const normalCount = 24;
        const abnormalCount = 1;
        const offlineCount = 0;
        const lowBatteryCount = 2;

        // 更新状态计数并添加动画效果
        const updateStatusValue = (id, value) => {
            const element = document.getElementById(id);
            if (element) {
                element.classList.add('updating');
                element.textContent = value;
                setTimeout(() => {
                    element.classList.remove('updating');
                }, 500);
            }
        };

        updateStatusValue('normal-count', normalCount);
        updateStatusValue('abnormal-count', abnormalCount);
        updateStatusValue('offline-count', offlineCount);
        updateStatusValue('low-battery-count', lowBatteryCount);

        // 更新状态图表
        this.charts.statusChart.data.datasets[0].data = [
            normalCount,
            abnormalCount,
            offlineCount,
            lowBatteryCount
        ];
        this.charts.statusChart.update();
    }

    startRealTimeUpdate() {
        // 每30秒更新一次数据
        setInterval(() => {
            this.updateData();
        }, 30000);
    }
}

// 创建实例
window.realtimeMonitoring = new RealtimeMonitoring(); 